package files

import (
	"fmt"
	"os"
	"sync"

	"gitee.com/xuender/oils/logs"
)

// App 应用.
type App struct {
	ctx *Context
	fs  *Service
}

// NewApp 新建应用.
func NewApp(
	ctx *Context,
	fs *Service,
) *App {
	return &App{
		ctx: ctx,
		fs:  fs,
	}
}

// Add 目录.
func (p *App) Add(paths []string) {
	logs.Debug("add", paths)

	if p.ctx.Remove {
		for _, path := range paths {
			p.fs.RemoveDir(path)
			p.fs.RemoveFiles(path)
		}
	} else {
		for _, path := range paths {
			p.fs.Add(path)
		}
	}

	for _, path := range p.fs.Dirs() {
		logs.Info("索引目录:", path)
	}

	p.fs.Index()
}

// Ignore 忽略目录.
func (p *App) Ignore(paths []string) {
	if p.ctx.Remove {
		for _, path := range paths {
			p.fs.RemoveIgnore(path)
		}
	} else {
		for _, path := range paths {
			p.fs.Ignore(path)
		}
	}

	p.fs.Index()
}

// Search 搜索.
func (p *App) Search(args []string) {
	var wg sync.WaitGroup

	wg.Add(1)

	go func() {
		p.fs.Index()
		wg.Done()
	}()

	logs.Debug("搜索", args)

	if p.ctx.Simple {
		for _, f := range p.fs.Search(args) {
			fmt.Fprintln(os.Stdout, f.Path)
		}

		return
	}

	logs.Info("找到:", p.fs.Count(args))

	for i, f := range p.fs.Search(args) {
		logs.Info(i+1, f.Path)
	}

	wg.Wait()
}
